package com.sigmazero13.gameutils;
import java.util.Formatter;
import java.util.List;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sigmazero13.gameutils.model.GameInfo;
import com.sigmazero13.gameutils.model.GameListParser;
import com.sigmazero13.gameutils.model.SyncInfo;
import com.sigmazero13.gameutils.utils.GameListAdapter;


public class GameList extends ListActivity {
	/** Called when the activity is first created. */
	private ProgressDialog progressDialog;
	
	public static final int GAME_BROWSE = 0;
	public static final int GAME_SINGLE_SELECT = 1;
	
	public static final int DIALOG_FILTER = 100;
	
	private List<GameInfo> games;
	private GameListAdapter adapter;
	
	private String filterName = null;
	private String filterPlayers = null;
	private String filterLength = null;
	
	private Dialog filterDialog;
	private EditText dialogName;
	private EditText dialogPlayers;
	private EditText dialogLength;
	
	private View filterInfo;
	private Button clearFilter;
	private TextView filterStatus;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_list);
        updateList();
        
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        
        Integer mode = 0;
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) 
        	mode = bundle.getInt("mode");
        
        View filterTap = findViewById(R.id.filter_info);
        filterTap.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openFilterDialog();
			}
		});
        
        filterInfo = findViewById(R.id.filter_info);
        filterStatus = (TextView)findViewById(R.id.filter_status_label);
        clearFilter = (Button)findViewById(R.id.filter_clear_button);
        clearFilter.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				clearFilter();
			}
		});
        
        switch (mode) {
        case GAME_BROWSE:
        	 // This is the default mode if no mode is sent
        	lv.setOnItemClickListener(new OnItemClickListener() {
        		@Override
        		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        			GameInfo thisGame = (GameInfo)parent.getItemAtPosition(position);
        		
        			Intent i = new Intent(GameList.this, GameInfoView.class);
        			i.putExtra("game_id", thisGame.getGameId());
        			startActivityForResult(i, 0);
        		}
        	});
        	break;
        case GAME_SINGLE_SELECT:
        	// This mode returns when an item is selected with the game id, for use as a "picker"
        	lv.setOnItemClickListener(new OnItemClickListener() {
        		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        			GameInfo thisGame = (GameInfo)parent.getItemAtPosition(position);
        			
        			Intent i = new Intent();
        			i.putExtra("gameId", thisGame.getGameId());
        			setResult(RESULT_OK, i);
        			finish();
        		}
        	});
        	break;
        }
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.list_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.preferences:
			Intent i = new Intent(GameList.this, GamePreferences.class);
			startActivity(i);
			break;
		case R.id.sync_option:
			new DownloadGamesTask().execute();
			break;
		case R.id.filter_games:
			openFilterDialog();
		}
		
		return true;
	}
	
	private void openFilterDialog() {
		showDialog(DIALOG_FILTER);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		if (id != DIALOG_FILTER) return null;
		
		filterDialog = new Dialog(this);
		filterDialog.setContentView(R.layout.game_filter_dialog);
		filterDialog.setTitle(R.string.filter_dialog_title);
		filterDialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
		
		dialogName = (EditText)filterDialog.findViewById(R.id.filter_name);
		dialogName.setText(filterName);
		dialogPlayers = (EditText)filterDialog.findViewById(R.id.filter_players);
		dialogPlayers.setText(filterPlayers);
		dialogLength = (EditText)filterDialog.findViewById(R.id.filter_length);
		dialogLength.setText(filterLength);
		
		Button apply = (Button)filterDialog.findViewById(R.id.filter_execute);
		apply.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				filterName = dialogName.getText().toString();
				filterPlayers = dialogPlayers.getText().toString();
				filterLength = dialogLength.getText().toString();
				filterDialog.dismiss();
				executeFilter();
			}
		});
		Button cancel = (Button)filterDialog.findViewById(R.id.filter_cancel);
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				filterDialog.dismiss();
			}
		});
		return filterDialog;
	}
	
	private void executeFilter() {
		if (filterName == null && filterPlayers == null && filterLength == null) {
			adapter.getFilter().filter(null);
			clearFilter.setVisibility(View.INVISIBLE);
			filterStatus.setText(R.string.filter_none);
			filterInfo.setBackgroundResource(R.color.filter_off);
		} else {
			if (filterName == null) filterName = "";
			if (filterPlayers == null) filterPlayers = "";
			if (filterLength == null) filterLength = "";
			filterName = filterName.replaceAll(";", "");
			adapter.getFilter().filter(filterName+";"+filterPlayers+";"+filterLength);
			clearFilter.setVisibility(View.VISIBLE);
			filterStatus.setText(R.string.filter_active);
			filterInfo.setBackgroundResource(R.color.filter_on);
		}
	}
	
	private void clearFilter() {
		filterName=null;
		filterPlayers=null;
		filterLength=null;
		dialogName.setText(null);
		dialogPlayers.setText(null);
		dialogLength.setText(null);
		executeFilter();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        boolean modified = false;
        Integer gameId = 0;
        if (intent != null) {
        	Bundle b = intent.getExtras();
        	modified = b.getBoolean("modified", false);
        	gameId = b.getInt("game_id", 0);
		}
    
       if (modified) {
    	   for (GameInfo game : games) {
    		   if (game.getGameId().equals(gameId)) {
    			   game.setCustomInfo(((BoardGameUtilsApp)GameList.this.getApplication()).getDbHelper().getCustomInfoForGame(game));
    			   break;
    		   }
    	   }
    	   ((ArrayAdapter<GameInfo>)getListAdapter()).notifyDataSetChanged();
       }
	}
	
	@Override
	public boolean onSearchRequested() {
		openFilterDialog();
		return false;
	}
    
    private void updateList() {
    	games = ((BoardGameUtilsApp)GameList.this.getApplication()).getDbHelper().selectAllGames();
    	adapter = new GameListAdapter(this, R.layout.list_item, games);
    	this.setListAdapter(adapter);
    }
 
    private void showLoadingDialog() {
    	progressDialog = new ProgressDialog(this);
    	progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	progressDialog.setMessage("Downloading game info...");
    	progressDialog.show();
    }
    
    private void closeLoadingDialog() {
    	progressDialog.dismiss();
    }
    
    private class DownloadGamesTask extends AsyncTask<Void, Void, List<GameInfo>> {
    	@Override 
    	protected void onPreExecute() {
    		showLoadingDialog();
    	}
    	
    	@Override
    	protected List<GameInfo> doInBackground(Void... nothing) {
    		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(GameList.this);
    		String username = prefs.getString("username", "");

    		if (username != null && !username.equals("")) {
    			Formatter f = new Formatter();
    			String bggUrl = f.format(GameList.this.getString(R.string.bgg_collection_url), username).out().toString();
    			GameListParser parser = new GameListParser(bggUrl);
    			return parser.parse();
    		} else {
    			return null;
    		}
    	}
    	
    	@Override
    	protected void onPostExecute(List<GameInfo> result) {
    		if (result != null) {
    			SyncInfo sync = ((BoardGameUtilsApp)GameList.this.getApplication()).getDbHelper().syncListWithDb(result);
    			Toast.makeText(getApplicationContext(), sync.toString(), Toast.LENGTH_SHORT).show();
    			updateList();
    		} else {
    			Toast.makeText(getApplicationContext(), "You must enter your username in the application settings!", Toast.LENGTH_SHORT).show();
    		}
    		
    		closeLoadingDialog();
    	}
    };
}
